package com.aluka.nirvana.framework.wechat.mina.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.aluka.nirvana.framework.wechat.mina.constant.MinaUrlConstant;
import com.aluka.nirvana.framework.wechat.mina.model.GetPaidUnionIdRequest;
import com.aluka.nirvana.framework.wechat.mina.model.GetPaidUnionIdResponse;
import com.aluka.nirvana.framework.wechat.mina.model.LoginRequest;
import com.aluka.nirvana.framework.wechat.mina.model.LoginResponse;

/**
 * 微信小程序公共通用场景API
 * · 登陆
 * · 用户信息
 * · 接口调用凭证
 * @author gongli
 * @since 2020/4/7 19:06
 */
public class MinaCommonApi extends BasicManaApi{


    /**
     * 通过前端[wx.login] 函数获得临时登录凭证code后需要再次通过微信小程序开发者服务器调用此接口完成登录流程
     * @param loginRequest 微信小程序登陆参数
     * @return 请求响应体
     */
    public LoginResponse loginMina(LoginRequest loginRequest){
        String url = appendParametersForGetRequestUrl(MinaUrlConstant.MINA_LOGIN_URL, loginRequest);
        HttpRequest request = HttpUtil.createGet(url);
        HttpResponse response = request.execute();
        return JSONUtil.toBean(response.body(), LoginResponse.class);
    }

    /**
     * 用户支付完成后，获取该用户的 UnionId，无需用户授权
     * 注意：调用前需要用户完成支付，且在支付后的五分钟内有效
     * @param paidUnionIdRequest 获取该用户的 UnionId 时所需的参数模型
     * @return 请求响应体
     */
    public GetPaidUnionIdResponse getPaidUnionId(GetPaidUnionIdRequest paidUnionIdRequest){
        String url = appendParametersForGetRequestUrl(MinaUrlConstant.MINA_LOGIN_URL, paidUnionIdRequest);
        HttpRequest request = HttpUtil.createGet(url);
        HttpResponse response = request.execute();
        return JSONUtil.toBean(response.body(),GetPaidUnionIdResponse.class);
    }


    private static class SingletonHolder{
        private static final MinaCommonApi INSTANCE = new MinaCommonApi();
    }

    public static MinaCommonApi getInstance(){
        return SingletonHolder.INSTANCE;
    }

    private MinaCommonApi (){};
}
